package com.example.shiwu.util;

import static androidx.constraintlayout.motion.utils.Oscillator.TAG;
//import static com.example.shiwu.SendReceiveAddActivity.saveBufferDataForTxt;

import android.content.Context;
import android.util.Log;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.SendReceiveAddActivity;
import com.example.shiwu.db.model.Alarm;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.service.AlarmService;
import com.example.shiwu.service.ItemsService;

import org.json.JSONException;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SocketMergeCallBackAlarmUtils implements Callback {

    public static Socket socket = null;
    public static InputStream mInputStream = null;
    public static OutputStream mOutStream = null;

    private static BufferedInputStream bmInputStream = null;
    private static BufferedOutputStream bmOutStream = null;
    public static boolean socketReconnection;
    private OnMessageReceivedListener messageListener;
    public static int success_count = 0;
    public static int success_count_maininfo = 0;
    public static int success_count_alram = 0;
    public static int clear_alram = 0;
    public static int header_cou = 0;
    public static String receiveDataAll = "";
    private String cmd_index_len = "";//消息的id 10
    public static Integer packet_lens = 0;
    public static Integer packet_indx = 0;
    public static int packet_lens_old = 0;
    public static int packet_indx_old = 0;
    public static Boolean isReConnect = false;
    public Boolean success8 = true;
    private static Boolean readClears = true;
    private int port = 8080;

    public static SocketReceiveThread mReceiveThread;
    public static SocketMainInfoThread mMainInfoThread;
    public static SocketAlarmThread mAlarmThread;
    public static SocketMergeCallBackAlarmUtils instance;

    public static int receive_count = 0;
    public static String msg_0 = "";
    public static String msg_1 = "";
    public static String dateStr = "";
    //public byte[] buffer;
    private Python py;
    private static PyObject pyobj;
    private static Context myContext;
    private static long timeouts = 13000;
    public int count59 = 0;
    public int sum59 = 8192;
    public static int bytecount = 0;

    private MyQueue queue;
    private MyQueue queueAlarm;
    public ArrayList<String> msgArray;
    public ArrayList<String> msgAlarmArray;
    private DataParseUtil dataParseUtil;
    public String alarmVal = "";
    private AlarmService alarmService;
    private ItemsService itemsService;


    public SocketMergeCallBackAlarmUtils(Context myContext) {
        try {
            socket = new Socket(ContextVariable.IP, this.port);
            socket.setTcpNoDelay(true);
            socket.setSendBufferSize(1024 * 1024);
            socket.setReceiveBufferSize(1024 * 1024);

            socket.setKeepAlive(true);

            //socket.setSoTimeout(4000);

            mInputStream = socket.getInputStream();
            mOutStream = socket.getOutputStream();
            if (mInputStream == null) {
                return;
            }

            initPython(myContext);
            queue = new MyQueue();
            queueAlarm = new MyQueue();
            msgArray = new ArrayList<>();
            msgAlarmArray = new ArrayList<>();
            dataParseUtil = new DataParseUtil();
            // 使用缓冲流进行数据传输
            bmInputStream = new BufferedInputStream(mInputStream);
            bmOutStream = new BufferedOutputStream(mOutStream);

            success_count = 0;
            Boolean sbl = isSocketConnected();
            if (sbl) {
                Log.i("info", "------------------socket 连接成功--------------- "+socket);
                Log.e("socket online","----------IO ---------"+mInputStream+mOutStream+bmInputStream+bmOutStream);

            } else {
                Log.i("info", "------------------socket 连接失败---------------");
            }

        } catch (IOException e) {
            isReConnect = true;
            e.printStackTrace();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean isSocketConnected() {
        return socket.isConnected() && !socket.isClosed();
    }

    private void initPython(Context myContext) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();
        //调用hello_python.py里面的plot函式
        pyobj = py.getModule("Send_Param");

    }


    public static synchronized SocketMergeCallBackAlarmUtils getInstance(Context myContext) {
        if (instance == null) {
            instance = new SocketMergeCallBackAlarmUtils(myContext);
        }
        return instance;
    }

    public void setOnMessageReceivedListener(OnMessageReceivedListener listener) {
        this.messageListener = listener;
        writeMsg("22,M;", new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "22,M; Text sent successfully ============= " + new String(data));
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Failed to send text: " + errorMessage);
            }
        });
        try {
            Thread.sleep(100);
            success_count = 1;
            writeMsg("22,M;", new Callback() {
                @Override
                public void onSuccess(byte[] data) {
                    Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                }

                @Override
                public void onFailure(String errorMessage) {
                    Log.e("SocketClient", "Failed to send text: " + errorMessage);
                }
            });
            Thread.sleep(1000);
            //success_count = 2;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void startListening() {
        dateStr = DateUtils.parseYmdHmsDate();
        if (socket != null) {
            try {

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void startListeningNew() {
        mReceiveThread = new SocketReceiveThread();
        mReceiveThread.start();

    }
//    public static void putDataToMyQueue(byte tmp) {
//        String temSta = String.valueOf(tmp)+" ";
//        if(String.valueOf(tmp).equals("85")){
//            temSta = "\r\n"+temSta;
//            saveBufferDataForTxt(temSta,dateStr);
//        }else{
//            saveBufferDataForTxt(temSta,dateStr);
//        }
//
//    }
    public static synchronized byte read() {
        byte[] buffer = new byte[1];
        if (readClears) {
            try {
                if (bmInputStream != null) {

                    int count = bmInputStream.read(buffer);
//                    putDataToMyQueue(buffer[0]);
                    bytecount += 1;
                    if (count == -1) {
                        Log.i(TAG, "read -1");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("socket_timeout","========== socket_timeout ======== ");
                try {
                    isReConnect = true;
                    releaseSocketNew();
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }

        return buffer[0];
    }

    public static synchronized byte[] readDataHead() {
        int count = 0;
        byte[] buffer = new byte[20];
        try {
            if (bmInputStream != null) {
                count = bmInputStream.read(buffer);
                bytecount += 1;
                if (count == -1) {
                    Log.i(TAG, "read -1");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("socket_timeout","=========== socket_timeout ======== ");
            try {
                isReConnect = true;
                releaseSocketNew();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }

        byte[] buffer2 = ArrayUtil.subByte(buffer, 0, count);
        return buffer2;
    }
    public static synchronized byte[] readDataHead14() {
        int count = 0;
        byte[] buffer = new byte[100];
        try {
            if (bmInputStream != null) {
                count = bmInputStream.read(buffer);
                bytecount += 1;
                if (count == -1) {
                    Log.i(TAG, "read -1");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("socket_timeout","socket ======== "+socket.isClosed());
            try {
                isReConnect = true;
                releaseSocketNew();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }

        byte[] buffer2 = ArrayUtil.subByte(buffer, 0, count);
        return buffer2;
    }
    public static synchronized byte[] readDataHead18() {
        int count = 0;
        byte[] buffer = new byte[30];
        try {
            if (bmInputStream != null) {
                count = bmInputStream.read(buffer);
                bytecount += 1;
                if (count == -1) {
                    Log.i(TAG, "read -1");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("socket_timeout","socket ======== "+socket.isClosed());
            try {
                isReConnect = true;
                releaseSocketNew();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }

        byte[] buffer2 = ArrayUtil.subByte(buffer, 0, count);
        return buffer2;
    }

    public static synchronized byte[] readDataHead16() {
        int count = 0;
        byte[] buffer = new byte[11];
        try {
            if (bmInputStream != null) {
                count = bmInputStream.read(buffer);
                bytecount += 1;
                if (count == -1) {
                    Log.i(TAG, "read -1");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("socket_timeout","socket ======== "+socket.isClosed());
            try {
                isReConnect = true;
                releaseSocketNew();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }

        byte[] buffer2 = ArrayUtil.subByte(buffer, 0, count);
        return buffer2;
    }

    public static synchronized Boolean read21() {
        byte[] buffer = new byte[2048];
        Boolean read21 = true;
        while (read21) {
            try {
                if (bmInputStream != null) {
                    int count = bmInputStream.read(buffer);
                    if (count == -1) {
                        Log.i(TAG, "---------------------------------------- read -1");
                    } else {
                       // Log.i(TAG, "---------------------------------------- read21==== " + Arrays.toString(buffer));
                    }
                }
            } catch (IOException e) {
                read21 = false;
                Log.e("read21", "------------ read21-----------------");
                e.printStackTrace();
            }
        }
        return read21;
    }

    public synchronized void readClear(int sta) {
        if (sta == 0) {
            readClears = true;

        } else if (sta == 1) {
            readClears = false;
            try {
                releaseSocketNew();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(mReceiveThread == null);
        }
    }

    public static void getTask() {
        try {
            //if (mInputStream.available() == 0) {
            success_count = 5;
            //byte[] data5 = pyobj.callAttr("onKReSync", packet_indx).toJava(byte[].class);
            Log.e("send_onKReSync","send_onKReSync_socket ======================"+socket.isClosed());
            writeMsg("22,M;", new Callback() {
                @Override
                public void onSuccess(byte[] data) {
                    Log.i("SocketClient", "Text sent successfully 22============= " + new String(data));
                }

                @Override
                public void onFailure(String errorMessage) {
                    Log.e("SocketClient", "Failed to send text: " + errorMessage);
                }
            });

            System.out.println("socketUtil_getTask 超时重复开始= " + DateUtils.parseYmdHmsDate());
            socketReconnection = true;
            SendReceiveAddActivity.recv_float_bool =  false;
            SendReceiveAddActivity.returnSta = false;
            SendReceiveAddActivity.receive_one_field_sta = false;
            SendReceiveAddActivity.boolErr = false;
            Thread.sleep(1000);
            //mReceiveThread.resumeThread();
            //}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeMsg(String msg) {
        Boolean sbl = isSocketConnected();
        if(!sbl){
            return;
        }
        //Log.i(TAG, "writeMsg msg=" + msg);
        if (msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
            Log.i(TAG, "-----------------writeMsg msg =" + msg + "   success_count=====" + success_count);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void writeMsg(String msg, Callback callback) {
        //Log.i(TAG, "writeMsg msg=" + msg);
        Boolean sbl = isSocketConnected();
        if(!sbl){
            return;
        }
        if (msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
            Log.i(TAG, "-----------------writeMsg msg =" + msg + "   success_count=====" + success_count);
            callback.onSuccess(readDataHead());
        } catch (IOException e) {
            e.printStackTrace();
            callback.onFailure("IOException: " + e.getMessage());
        }

    }
    public static void writeMsg18(String msg, Callback callback) {
        //Log.i(TAG, "writeMsg msg=" + msg);
        Boolean sbl = isSocketConnected();
        if(!sbl){
            return;
        }
        if (msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
            Log.i(TAG, "-----------------writeMsg msg =" + msg + "   success_count=====" + success_count);
            callback.onSuccess(readDataHead18());
        } catch (IOException e) {
            e.printStackTrace();
            callback.onFailure("IOException: " + e.getMessage());
        }

    }

    public static void writeMsg14(String msg, Callback callback) {
        //Log.i(TAG, "writeMsg msg=" + msg);
        Boolean sbl = isSocketConnected();
        if(!sbl){
            return;
        }
        if (msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
            Log.i(TAG, "-----------------writeMsg msg =" + msg + "   success_count=====" + success_count);
            callback.onSuccess(readDataHead14());
        } catch (IOException e) {
            e.printStackTrace();
            callback.onFailure("IOException: " + e.getMessage());
        }

    }

    public static void writeMsgByte(byte[] msg, Callback callback) {
        Boolean sbl = isSocketConnected();
        if(!sbl){
            return;
        }
        Log.i(TAG, "----------------- alarm writeMsgByte msg mOutStream      =" + mOutStream + "   success_count=====" + success_count);

        if (msg.length == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg);//发送
            mOutStream.flush();
            Log.i(TAG, "-----------------writeMsgByte msg =" + new String(msg) + "   success_count=====" + success_count);
            if (null != mReceiveThread) {
                mReceiveThread.resumeThread();
            }
            callback.onSuccess(readDataHead());
        } catch (IOException e) {
            e.printStackTrace();
            callback.onFailure("IOException: " + e.getMessage());
        }

    }
    public static void writeMsgByte(byte[] msg) {
        Boolean sbl = isSocketConnected();
        if(!sbl){
            return;
        }
        if (msg.length == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg);//发送
            mOutStream.flush();
            Log.i(TAG, "-----------------writeMsgByte msg 1111=" + new String(msg) + "   success_count=====" + success_count);
            if (null != mReceiveThread) {
                mReceiveThread.resumeThread();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void writeMsgByte16(byte[] msg, Callback callback) {
        Boolean sbl = isSocketConnected();
        if(!sbl){
            return;
        }
        if (msg.length == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg);//发送
            mOutStream.flush();
            Log.i(TAG, "-----------------writeMsgByte msg =" + new String(msg) + "   success_count=====" + success_count);
            if (null != mReceiveThread) {
                mReceiveThread.resumeThread();
            }
            callback.onSuccess(readDataHead16());
        } catch (IOException e) {
            e.printStackTrace();
            callback.onFailure("IOException: " + e.getMessage());
        }

    }

    public void closeConnection() {
        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*释放资源*/
    public void releaseSocket() {

        instance = null;

        if (mOutStream != null) {
            try {
                mOutStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            mOutStream = null;
        }
        if (mInputStream != null) {
            try {
                mInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mInputStream = null;
        }

        if (socket != null) {
            try {
                socket.close();

            } catch (IOException e) {
            }
            socket = null;
        }

        /*重新初始化socket*/
        if (isReConnect) {
            socket = null;
            mInputStream = null;
            mOutStream = null;
            isReConnect = false;
        }
    }

    public static synchronized void releaseSocketNew() throws InterruptedException {
        read21();
        instance = null;
        if (mOutStream != null) {
            try {
                mOutStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
            mOutStream = null;
        }
        if (mInputStream != null) {
            try {
                mInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mInputStream = null;
        }
        if(bmInputStream != null){
            try {
                bmInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            bmInputStream = null;
        }
        if(bmOutStream != null){
            try {
                bmOutStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            bmOutStream = null;
        }

        if (socket != null) {
            try {
                socket.close();

            } catch (Exception e) {
            }
            socket = null;
        }

        /*重新初始化socket*/
        if (isReConnect) {
            socket = null;
//            mInputStream = null;
//            mOutStream = null;
            instance = new SocketMergeCallBackAlarmUtils(myContext);
            System.out.println("___________________socket重连_______________");
            if (socket == null) {
                System.out.println("___________________socket重连1111111111111_______________");
                instance = new SocketMergeCallBackAlarmUtils(myContext);
                Thread.sleep(1500);
                isReConnect = false;
                getTask();
            }else{
                Thread.sleep(1500);
                isReConnect = false;
               getTask();
            }
            socketReconnection = true;
            SendReceiveAddActivity.recv_float_bool =  false;
            SendReceiveAddActivity.returnSta = false;
            SendReceiveAddActivity.receive_one_field_sta = false;
            SendReceiveAddActivity.boolErr = false;
            Thread.sleep(1000);
        }
    }

//    @Override
//    public void onSuccess(String result) {
//        System.out.println("操作成功，结果为：" + result);
//    }

    @Override
    public void onSuccess(byte[] data) {
        System.out.println("发送成功信息为：" + new String(data));
    }

    @Override
    public void onFailure(String error) {
        System.out.println("操作失败，错误信息为：" + error);
    }

    public interface OnMessageReceivedListener {
        void onMessageReceived(byte message);

        void onMessageReceivedString(String message);

        void onConnectionLost();
    }

    public static void resumeThread() {
        mReceiveThread.resumeThread();
    }

    public static void pauseThread() {
        mReceiveThread.pauseThread();
    }


    class SocketReceiveThread extends Thread {
        public final Object lock = new Object();
        public boolean threadExit;


        public SocketReceiveThread() {
            threadExit = false;
        }

        /**
         * 调用这个方法实现暂停线程
         */
        public void pauseThread() {
            threadExit = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        public void resumeThread() {
            threadExit = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void threadExit() {
            threadExit = true;
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        public void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            //System.out.println("-------threadExitrunrunrunrunrun == "+threadExit);
            String msg1 = "";

            while (threadExit == false) {

                //System.out.println("-------threadExit1111111111111111111111111 == ");
                try {
                    byte[] buffer = new byte[1];
                    //读取数据，返回值表示读到的数据长度。-1表示结束
                    int count = 0;
                    try {
                        //基于字符的读取或基于字节的读取
                        count = bmInputStream.read(buffer);

                        //int bytesRead = mInputStream.read(buffer);
                        if (count == -1) {
                            Log.i(TAG, "read -1");
                            break;
                        } else {
                            // System.out.println("---- buffer = "+buffer);
                            //Log.i(TAG, "==========采集数据==========");
                            if (success_count <= 5) {
                                String msg00 = new String(buffer, "utf-8");
                                msg_0 += new String(buffer, "utf-8");
                                //System.out.println("---msg00 =" + msg00+" - "+buffer[0]);
                                try {
                                    if (msg00.equals("??")) {
                                        System.out.println("PC usb dis-connected");
                                        throw new Exception("PC usb dis-connected");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                String obj = receive_one_field(1);//过滤header
                                String msg_all = msg_0 += obj;
                                // System.out.println("---msg_all =" + msg_all +" success_count = "+success_count);

                                if (msg_all.length() > 2) { //msg_all(0,success) len超过2 也就是0，就可以返回了
                                    if (msg_all.equals("0,Success;")) {
                                        success_count += 1;
                                    }
                                    messageListener.onMessageReceivedString(msg_all);
                                    msg_0 = "";
                                }
                                //System.out.println("---msg_all =" + msg_all +" success_count = "+success_count);
//                                if(success_count == 5){
//                                    success_count += 1;
//                                }

                            } else if (success_count == 6) {
                                msg_0 = new String(buffer, "iso8859-1");

                                System.out.println("---msg msg_0 6666 =" + msg_0);
                                try {
                                    if (msg_0.equals("??")) {
                                        System.out.println("PC usb dis-connected");
                                        throw new Exception("PC usb dis-connected");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                String obj = receive_one_field(2);//过滤header
                                String msg_all = msg_0 += obj;
                                System.out.println("---msg_all11 666 =" + msg_all);
                                String msg_all_last = msg_all.substring(msg_all.length() - 1, msg_all.length());
                                if (!msg_all_last.equals(";")) {
                                    msg_1 += msg_all;
                                    continue;
                                }
                                if (msg_all_last.equals(";")) { //msg_all(10,8) 截取数据

                                    success_count += 1;
                                    msg_1 += msg_all;
                                    receiveDataAll += msg_1;
                                    System.out.println("---receiveDataAll =" + receiveDataAll);
                                    if (receiveDataAll.equals("0,Success;")) {
                                        success_count = 6;
                                        receiveDataAll = "";
                                        msg_1 = "";
                                        continue;
                                    } else if (receiveDataAll.equals("0,wait;")) {
                                        success_count = 6;
                                        receiveDataAll = "";
                                        msg_1 = "";
                                        continue;
                                    } else if (receiveDataAll.equals("0,alarm;")) {//告警
                                        System.out.println("============= 告警 =================");
                                        success_count = 1;
                                        messageListener.onMessageReceivedString(receiveDataAll);
                                        this.onPause();
                                        break;
                                    } else if (receiveDataAll.equals("0,")) {
                                        success_count = 6;
                                        receiveDataAll = "";
                                        msg_1 = "";
                                        continue;
                                    }
                                    try {
                                        System.out.println("--------success_count == 77777777777777777777777777777");

                                        if (success_count == 7) {
                                            System.out.println("--------success_count == 7----------------------------");

                                            cmd_index_len = DataParseUtil.getDataForHeaderIndex(receiveDataAll);
                                            packet_indx = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[1]));

                                            packet_lens = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[2]));
                                            System.out.println("--------mReceiveThread22222  packet_indx==" + packet_indx + " = " + packet_lens + " = " + success_count);
                                            packet_lens_old = packet_lens;
                                            packet_indx_old = packet_indx;
                                            DataParseUtil.setPageLens(packet_lens);
                                            receiveDataAll = "";
                                        }
                                        msg_0 = "";
                                        msg_1 = "";
                                    } catch (Exception e) {
                                        //getTask();
                                        e.printStackTrace();
                                        //success_count = 8;
                                    }
                                }
                            } else {
                                if (success_count == 7) {
                                    Log.i("buffer", "-------------success_count777 =7");
                                    success_count += 1;
                                    this.onPause();

                                    continue;
                                }
                                if (success_count > 7) {
                                    bytecount += 1;
                                    //Log.i("buffer","-------------success_count >6 -----------= " + new String(buffer));
                                    //Log.i("buffer","-------------success_count >6 -----------= " + buffer[0]);
                                    //Log.i("buffer", "-------------bytecount -----------= " + bytecount);
//                                        messageListener.onMessageReceived(buffer[0]);
//                                        buffer = null;
                                }
                            }
                        }
                        //this.pauseThread();
                        //}else {
                        //this.pauseThread();
                        //}

                    } catch (Exception e) {
                        Log.i(TAG, "read count=" + count);
                        System.out.println("------- SocketReceiveThread releaseSocketNew----");
//                        isReConnect = true;
//                        releaseSocketNew();

                        e.printStackTrace();
                        // messageListener.onMessageReceivedString("null");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            System.out.println("-------threadExit222222222222222222222222 == " + threadExit);
        }
    }


    private synchronized String receive_one_field(int sta) throws InterruptedException, UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean timeout = false;
        Boolean bl = true;
        String msgbt = "";
        while (bl) {
            byte tmp = this.read();
            byte[] b = new byte[1];
            b[0] = tmp;
            if (sta == 1) {
                msgbt += new String(b, "utf-8");
            } else {
                msgbt += new String(b, "iso8859-1");
            }

            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }

        }

        map.put("one_field", one_field);
        map.put("timeout", timeout);
        return msgbt;
    }

    public void stopListening() {
        mReceiveThread.threadExit();

    }

    /************************* MainInfo  ***************************/

    class SocketMainInfoThread extends Thread {
        public final Object lock = new Object();
        public boolean threadExitMainInfo;


        public SocketMainInfoThread() {
            threadExitMainInfo = false;
        }

        /**
         * 调用这个方法实现暂停线程
         */
        public void pauseThread() {
            threadExitMainInfo = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        public void resumeThread() {
            threadExitMainInfo = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void threadExit() {
            threadExitMainInfo = true;
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        public void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {

            while (threadExitMainInfo == false) {
                //Log.i(TAG, "==========threadExitMainInfo:===================" + threadExitMainInfo);
                try {
                    byte[] buffer = new byte[512];
                    //读取数据，返回值表示读到的数据长度。-1表示结束
                    int count = 0;
                    try {
                        if (mInputStream.available() > 0) {
                            count = mInputStream.read(buffer);
                            if (count == -1) {
                                Log.i(TAG, "read -1");
                                break;
                            } else {
                                //基于字符的读取或基于字节的读取
                                Log.i(TAG, "==========maininfo==========");
                                String receiveData = new String(buffer, 0, count);
                                Log.i(TAG, "==========read buffer:" + receiveData + ",count=" + count);
                                //Log.i(TAG, "==========read buffer1111:" + buffer );

                                String msgCode = receiveData.substring(2, receiveData.indexOf(";"));
                                Log.i(TAG, "==========read buffer msgCode:" + msgCode);
                                if (msgCode.contains("Success")) {
                                    success_count_maininfo += 1;
                                    if (success_count_maininfo == 2) {
                                        writeMsg("11,s;18,get;13,update;", new Callback() {
                                            @Override
                                            public void onSuccess(byte[] data) {
                                                Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                                            }

                                            @Override
                                            public void onFailure(String errorMessage) {
                                                Log.e("SocketClient", "Failed to send text: " + errorMessage);
                                            }
                                        });

                                    }
                                    if (success_count_maininfo > 2) {
                                        Log.i(TAG, "==========read buffer success_count > 2========================" + msgCode);
                                    }
                                } else {
                                    int semicolon_inx = ByteUtil.bByteForSemicolon(buffer, 0);
                                    String box_add = msgCode.substring(1, msgCode.length());
                                    int semicolon_inx2 = ByteUtil.bByteForSemicolon(buffer, semicolon_inx + 1);
                                    byte[] byte_18 = ByteUtil.subByte(buffer, semicolon_inx + 1, semicolon_inx2);
                                    byte[] byte_14 = ByteUtil.subByte(buffer, semicolon_inx2 + 4, count - semicolon_inx2 - 4);
                                    for (byte b : byte_14) {
                                        queue.enQueue(b);
                                    }
                                    String msglis_18 = ByteUtil.byteTransformAscil(byte_18);
                                    //System.out.println("  msglis_18 ===================="+ msglis_18);
                                    String mas_18_val = msglis_18.split(";")[0].replace("18, ", "");//固件版本

                                    Double batt_vol = Double.valueOf(receive_one_field_maininfo());//电源
                                    System.out.println("  电源电压 ====================" + batt_vol);
                                    String tx_high_vol1 = receive_one_field_maininfo();//高压
                                    String tx_high_vol = "";
                                    if (tx_high_vol1.length() > 1) {
                                        tx_high_vol = tx_high_vol1.substring(0, tx_high_vol1.indexOf(".")) + "V";//主机电压
                                    } else {
                                        tx_high_vol = tx_high_vol1 + "V";//温度
                                    }
                                    String temperature1 = receive_one_field_maininfo();//温度
                                    System.out.println("  温度 ====================" + temperature1);
                                    String temperature = "";
                                    if (temperature1.length() > 1) {
                                        temperature = temperature1.substring(0, temperature1.indexOf(".")) + "°C";//温度
                                    } else {
                                        temperature = temperature1 + "°C";//温度
                                    }
                                    String humidity1 = receive_one_field_maininfo();//湿度

                                    String humidity = "";//湿度
                                    if (humidity1.length() > 1) {
                                        humidity = humidity1.substring(0, humidity1.indexOf(".")) + "°C";//湿度
                                    } else {
                                        humidity = humidity1 + "°C";
                                    }

                                    int batt_vol_int = batt_vol.intValue();
                                    BigDecimal a = new BigDecimal(batt_vol_int);
                                    BigDecimal b = new BigDecimal(ContextVariable.power_supply);
                                    BigDecimal c = a.divide(b, 2, BigDecimal.ROUND_HALF_DOWN);
                                    String batt_percent = String.valueOf(c.multiply(new BigDecimal(100)));
                                    int batt_percent_val1 = Integer.parseInt(batt_percent.substring(0, batt_percent.indexOf(".")));
                                    if (batt_percent_val1 > 100) {
                                        batt_percent_val1 = 100;
                                    }
                                    String batt_percent_val = batt_percent_val1 + "%";
                                    msgArray.add(box_add);
                                    msgArray.add(mas_18_val);
                                    msgArray.add(batt_percent_val);
                                    msgArray.add(ContextVariable.channel);
                                    msgArray.add(tx_high_vol);
                                    msgArray.add(temperature);
                                    msgArray.add(humidity);
                                    if (success_count_maininfo == 3) {//发送到页面
                                        success_count_maininfo = 0;
                                        queue.clear();
                                        //msgAlarmArray.clear();
                                        threadExitMainInfo = true;
                                        onPause();

                                        //releaseSocket();
                                    }
                                }
                            }
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                        //messageListener.onMessageReceivedString("null");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            System.out.println("-------threadExitmaininfo == " + threadExitMainInfo);
        }
    }

    public void startMainInfoListening() {
        mMainInfoThread = new SocketMainInfoThread();
        mMainInfoThread.start();
        writeMsg("22,M;", new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Failed to send text: " + errorMessage);
            }
        });

        try {
            Thread.sleep(100);
            success_count_maininfo = 0;
            writeMsg("22,M;", new Callback() {
                @Override
                public void onSuccess(byte[] data) {
                    Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                }

                @Override
                public void onFailure(String errorMessage) {
                    Log.e("SocketClient", "Failed to send text: " + errorMessage);
                }
            });
            success_count_maininfo = 1;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    public void stopMainInfoListening() {
        mMainInfoThread.pauseThread();

    }

    private synchronized String receive_one_field_maininfo() throws InterruptedException, UnsupportedEncodingException {
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean bl = true;
        String msgbt = "";
        while (bl) {

            byte tmp = (byte) queue.deQueue();
            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }

        }
        if (one_field.size() > 0) {
            //System.out.println("------one_field-------" + one_field);
            msgbt = recv_float_maininfo(one_field);
        }

        return msgbt;
    }

    private String recv_float_maininfo(ArrayList<Byte> val) {
        List<Byte> ab5 = dataParseUtil.objToByList(val);
        byte[] str_one_field5 = dataParseUtil.listTobyte(ab5);
        if (str_one_field5.length == 1) {
            return String.valueOf(str_one_field5[0]);
        }
        return dataParseUtil.recv_float(str_one_field5);
    }


    /************************************  AlarmSocket *************************************/

    class SocketAlarmThread extends Thread {
        public final Object lock = new Object();
        private boolean threadExit;
        private int blen = 1024;

        public SocketAlarmThread() {
            threadExit = false;
        }

        /**
         * 调用这个方法实现暂停线程
         */
        public void pauseAlarmThread() {
            threadExit = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        public void resumeAlarmThread() {
            threadExit = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void threadAlarmExit() {
            threadExit = true;
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        public void onPauseAlarm() {
            synchronized (lock) {
                try {
                    threadExit = true;
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void run() {
            byte[] buffer = new byte[blen];
            int count = 0;
            while (threadExit == false) {
                try {
                    //读取数据，返回值表示读到的数据长度。-1表示结束
                    if(mInputStream == null){
                        threadExit = true;
                        break;
                    }
                    if (mInputStream.available() > 0) {
                        count = mInputStream.read(buffer);
                        if (count == -1) {
                            Log.i(TAG, "read read -1");
                            break;
                        } else {
                            Log.i(TAG, "==========ALAMR==========");
                            String receiveData = new String(buffer, 0, count);
                            //Log.i(TAG, "==========read buffer:" + receiveData + ",count=" + count);
                            //Log.i(TAG, "==========read buffer1111:" + buffer );

                            String msgCode = receiveData.substring(2, receiveData.indexOf(";"));
                            Log.i(TAG, "==========alarm msgCode:" + msgCode);
                            if (msgCode.equals("Success")) {
                                success_count_alram += 1;
                                if (success_count_alram == 2) {  //告警列表
                                    writeMsg("18,get;13,update;", new Callback() {
                                        @Override
                                        public void onSuccess(byte[] data) {
                                            Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                                        }

                                        @Override
                                        public void onFailure(String errorMessage) {
                                            Log.e("SocketClient", "Failed to send text: " + errorMessage);
                                        }
                                    });
                                    success_count_alram = 0;
                                } else { //清除告警
                                    if (clear_alram != 0) {
                                        alarmVal = "告警已解除！";
                                        msgAlarmArray.add(alarmVal);
                                    }
                                }
                            } else if (msgCode.equals("alarm")) {
                                success_count_alram += 1;
                                if (success_count_alram == 2) {
                                    writeMsg("18,get;13,update;", new Callback() {
                                        @Override
                                        public void onSuccess(byte[] data) {
                                            Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                                        }

                                        @Override
                                        public void onFailure(String errorMessage) {
                                            Log.e("SocketClient", "Failed to send text: " + errorMessage);
                                        }
                                    });
                                    success_count_alram = 0;
                                }
                            } else {
                                int semicolon_inx = ByteUtil.bByteForSemicolon(buffer, 0);
                                byte[] byte_18 = ByteUtil.subByte(buffer, 0, semicolon_inx);
                                byte[] byte_14 = ByteUtil.subByte(buffer, semicolon_inx + 4, count - semicolon_inx - 4);
                                for (byte b : byte_14) {
                                    queueAlarm.enQueue(b);
                                }
                                String msglis_18 = ByteUtil.byteTransformAscil(byte_18);
                                //System.out.println("  msglis_18 ===================="+ msglis_18);
                                String mas_18_val = msglis_18.split(",")[1];//固件版本

                                Double batt_vol = Double.valueOf(receive_one_field_alarm());//电源
                                System.out.println("  电源电压 ====================" + batt_vol);
                                String tx_high_vol = receive_one_field_alarm();//高压

                                String temperature1 = receive_one_field_alarm();//温度
                                String humidity1 = receive_one_field_alarm();//湿度
                                String alarm = receive_one_field_alarm();//告警
                                //String outEle = receive_one_field_alarm();//外部电源
//                                String alarmVal = "";
                                System.out.println("  alarm ====================" + alarm);
                                switch (alarm) {
                                    case "2":
                                        alarmVal = "RX接受的电压超最大量程范围";
                                        break;
                                    case "5":
                                        alarmVal = "电池电压低";
                                        break;
                                    case "6":
                                        alarmVal = "高压未达到预设值";
                                        break;
                                    case "7":
                                        alarmVal = "用户主动紧急停止 或 TX电流超范围";
                                        break;
                                }
                                System.out.println("  alarm ====================" + alarm);
                                if (!alarm.equals("0")) {
                                    msgAlarmArray.add(alarmVal);
                                    msgAlarmArray.add(mas_18_val);
                                    Items items = findSelectItem();
                                    String itemsId = items.getId().toString();
                                    alarmService = new AlarmService();
                                    Alarm alarm1 = new Alarm();
                                    alarm1.setAlarmMsg(alarmVal);
                                    alarm1.setSn(mas_18_val);
                                    alarm1.setItemId(itemsId);
                                    alarm1.setStatus(0);
                                    SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                    Date date = new Date(System.currentTimeMillis());
                                    alarm1.setCreateTime(sim.format(date));
                                    alarm1.setUpdateTime(sim.format(date));
                                    alarmService.save(alarm1);
                                    //msgAlarmArray.clear();
                                    onPauseAlarm();
                                } else {
                                    onPauseAlarm();
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    System.out.println("+++++++++++++++ receive +++++++++++++++");
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    //throw new RuntimeException(e);
                    e.printStackTrace();
                }

            }
        }

        void threadExit() {
            threadExit = true;
        }
    }


    public synchronized String receive_one_field_alarm() throws InterruptedException, UnsupportedEncodingException {
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean bl = true;
        String msgbt = "";
        while (bl) {

            byte tmp = (byte) queueAlarm.deQueue();
            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }

        }
        if (one_field.size() > 0) {
            msgbt = recv_float_alarm(one_field);
        }

        return msgbt;
    }

    private String recv_float_alarm(ArrayList<Byte> val) {
        List<Byte> ab5 = DataParseUtil.objToByList(val);
        byte[] str_one_field5 = DataParseUtil.listTobyte(ab5);
        if (str_one_field5.length == 1) {//告警
            return String.valueOf(str_one_field5[0]);
        }
        return DataParseUtil.recv_float(str_one_field5);
    }

    public void startAlarmListening() {
//        mAlarmThread = new SocketAlarmThread();
//        mAlarmThread.start();
        writeMsg("22,M;", new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Failed to send text: " + errorMessage);
            }
        });

        try {
            Thread.sleep(100);
            success_count_alram = 0;
            writeMsg("22,M;", new Callback() {
                @Override
                public void onSuccess(byte[] data) {
                    Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                }

                @Override
                public void onFailure(String errorMessage) {
                    Log.e("SocketClient", "Failed to send text: " + errorMessage);
                }
            });
            success_count_alram = 1;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    public void stopAlarmListening() {
        mAlarmThread.threadAlarmExit();

    }

    public Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }
}


